<template>
  <div v-if="!isLogin && props.needLogin" class="header-login-entry">
    <span>登录</span>
  </div>
  <div v-else class="header-avatar" @click="naviToUserPage">
<!--    <img :src="avatarUrl || userInfo.avatarUrl" alt="" />-->
    <img src="https://ts1.cn.mm.bing.net/th/id/R-C.738148bdb2da83e7bab5d7f63d1190cd?rik=usj6CNEFf1B92w&riu=http%3a%2f%2fpic.baike.soso.com%2fp%2f20140311%2f20140311162033-282564199.jpg&ehk=eRgO3fxJa6CqLG1pjx7VaCyEV5qGOTFOR9r3yG1veYA%3d&risl=&pid=ImgRaw&r=0" alt="" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import User from '@/utils/User/User.js';
import {useRouter} from "vue-router";

const router = useRouter();
const props = defineProps({
  avatarUrl: {
    type: String,
    default: null,
  },
  needLogin: {
    type: Boolean,
    default: false,
  }
});

const isLogin = ref(User.isLogin());
const userInfo = ref({ avatarUrl: null });

// 导航至用户首页
const naviToUserPage = ()=>{
  router.push({
    name: 'user',
    params: {
      userid: userInfo.value.userid,
    }
  })
}

// 获取用户信息
const fetchUserInfo = async () => {
  if (isLogin.value ) {
    try {
      const info = await User.getUserInfo();
      userInfo.value = info;
    } catch (error) {
      console.error('Failed to fetch user info:', error);
    }
  }
};
// 监听登录状态变化
// watch(() => User.isLogin(), (newVal) => {
//   isLogin.value = newVal;
//   if (newVal) {
//     fetchUserInfo();
//   } else {
//     userInfo.value = { avatarUrl: null };
//   }
// });
onMounted(() => {
  if (!props.avatarUrl) {
    console.log('获取header info')
    fetchUserInfo();
  }
});

</script>

<style scoped>
.header-login-entry, .header-avatar {
  cursor: pointer;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 !important;
  padding: 0 !important; ;
}


.header-login-entry span {
  color: #007bff;
  font-size: 14px;
  line-height: 18px;
}

.header-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
</style>
